using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Diagnostics;
using WPF_MVVM_Test.MVVM_Model;

namespace WPF_MVVM_Test.Services
{
    public class AiChatService
    {
        private readonly HttpClient _httpClient;
        private const string CHAT_API_URL = "http://8.140.51.34:44394/api/app/kou-zi-aI/send-stream-merged";

        public AiChatService()
        {
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Add("accept", "text/plain");
            _httpClient.Timeout = TimeSpan.FromMinutes(10); // 增加到10分钟
        }

        public async Task SendMessageStreamAsync(ChatRequest request, Action<string> onDataReceived, Action onCompleted, Action<Exception> onError)
        {
            try
            {
                Debug.WriteLine($"发送请求: {JsonSerializer.Serialize(request)}");
                var jsonContent = JsonSerializer.Serialize(request);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                // 发送API请求
                using var response = await _httpClient.PostAsync(CHAT_API_URL, content);
                
                if (!response.IsSuccessStatusCode)
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    Debug.WriteLine($"API请求失败: {response.StatusCode}, 内容: {errorContent}");
                    onError?.Invoke(new Exception($"API请求失败: {response.StatusCode}, 内容: {errorContent}"));
                    return;
                }

                var responseText = await response.Content.ReadAsStringAsync();
                Debug.WriteLine($"收到原始响应: {responseText}");

                // 如果响应为空，返回一个默认消息
                if (string.IsNullOrEmpty(responseText))
                {
                    Debug.WriteLine("响应为空，返回默认消息");
                    onDataReceived?.Invoke("抱歉，我没有收到有效的回复。");
                    onCompleted?.Invoke();
                    return;
                }

                // 尝试解析为 ChatResponse 对象
                try
                {
                    var chatResponse = JsonSerializer.Deserialize<ChatResponse>(responseText);
                    
                    if (chatResponse != null)
                    {
                        // 检查是否成功
                        if (!chatResponse.Success)
                        {
                            var errorMessage = !string.IsNullOrEmpty(chatResponse.ErrorMessage) 
                                ? chatResponse.ErrorMessage 
                                : "未知错误";
                            
                            Debug.WriteLine($"API返回失败: {errorMessage}");
                            onError?.Invoke(new Exception($"API返回失败: {errorMessage}"));
                            return;
                        }
                        
                        // 提取内容
                        if (!string.IsNullOrEmpty(chatResponse.Content))
                        {
                            Debug.WriteLine($"提取的内容: {chatResponse.Content}");
                            onDataReceived?.Invoke(chatResponse.Content);
                            onCompleted?.Invoke();
                            return;
                        }
                    }
                    
                    // 如果无法从对象中获取内容，尝试直接解析JSON
                    var jsonDoc = JsonDocument.Parse(responseText);
                    Debug.WriteLine($"解析的JSON: {jsonDoc.RootElement}");
                    
                    // 尝试从JSON中提取内容
                    if (jsonDoc.RootElement.TryGetProperty("content", out var contentProp))
                    {
                        var extractedContent = contentProp.GetString();
                        if (!string.IsNullOrEmpty(extractedContent))
                        {
                            Debug.WriteLine($"从JSON提取的内容: {extractedContent}");
                            onDataReceived?.Invoke(extractedContent);
                            onCompleted?.Invoke();
                            return;
                        }
                    }
                    
                    // 如果仍然无法提取内容，返回默认消息
                    Debug.WriteLine("无法提取内容，返回默认消息");
                    onDataReceived?.Invoke("抱歉，我无法理解服务器的响应。");
                }
                catch (JsonException ex)
                {
                    // JSON解析失败，返回错误消息
                    Debug.WriteLine($"JSON解析失败: {ex.Message}");
                    onDataReceived?.Invoke("抱歉，服务器返回的数据格式有误。");
                }

                onCompleted?.Invoke();
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"发生异常: {ex}");
                onError?.Invoke(ex);
            }
        }
        
        private string ExtractContentFromJson(JsonElement root)
        {
            // 根据提供的实际API响应格式，直接尝试获取content字段
            if (root.TryGetProperty("content", out var contentProp))
            {
                var content = contentProp.GetString();
                if (!string.IsNullOrEmpty(content))
                {
                    Debug.WriteLine("从content属性提取内容");
                    return content;
                }
            }
            
            // 检查API返回的错误信息
            if (root.TryGetProperty("errorMessage", out var errorProp) && 
                !errorProp.ValueKind.Equals(JsonValueKind.Null))
            {
                var errorMessage = errorProp.GetString();
                if (!string.IsNullOrEmpty(errorMessage))
                {
                    Debug.WriteLine($"API返回错误: {errorMessage}");
                    return $"API错误: {errorMessage}";
                }
            }
            
            // 如果无法直接获取content，尝试其他可能的路径
            if (root.TryGetProperty("choices", out var choices) && choices.GetArrayLength() > 0)
            {
                var choice = choices[0];
                
                if (choice.TryGetProperty("message", out var message) && 
                    message.TryGetProperty("content", out var messageContent))
                {
                    var content = messageContent.GetString();
                    if (!string.IsNullOrEmpty(content))
                    {
                        Debug.WriteLine("从choices[0].message.content提取内容");
                        return content;
                    }
                }
            }
            
            // 如果所有尝试都失败，返回原始JSON
            Debug.WriteLine("无法从JSON中提取内容，返回null");
            return null;
        }

        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }
}